<%-- Created by IntelliJ IDEA. User: Administrator Date: 2022/12/3 Time: 22:26
To change this template use File | Settings | File Templates. --%>
<%@ page
        contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>所有用户</title>
    <jsp:include page="../../common/css_js.jsp"/>
    <jsp:include page="../../common/table.jsp"/>
</head>
<body>
<div class="container col-lg-12">
    <div class="card">
        <header class="card-header">
            <div class="card-title">
                <b style="font-size: 25px">用户列表--所有用户信息</b>
            </div>
        </header>
        <div class="card-body">
            <form
                    class="form-inline"
                    name="form1"
                    action="#"
                    method="post"
                    id="toolbar"
            >
                &nbsp;&nbsp;&nbsp;
                <a class="btn btn-primary" href="#" onclick="toAdd()"
                ><span class="mdi mdi-plus"></span>新增用户</a
                >
                &nbsp;
                <a class="btn btn-danger" href="#" onclick="batchDel()"
                ><span class="mdi mdi-delete"></span>批量删除</a
                >
                &nbsp;
                <a class="btn btn-primary" href="#" onclick="query()"
                ><span class="mdi mdi-table-large"></span>显示所有</a
                >
                &nbsp;&nbsp;
                <b>用户名：</b>
                <label>
                    <input
                            name="username"
                            style="width: 150px"
                            placeholder="请输入用户名称"
                            class="form-control"
                    /> </label
                >&nbsp;&nbsp;
                <b>联系电话：</b>
                <label>
                    <input
                            name="userPhone"
                            style="width: 150px"
                            placeholder="请输入联系电话"
                            class="form-control"
                    /> </label
                >&nbsp;
                <button type="button" class="btn btn-primary" onclick="like()">
                    <span class="mdi mdi-table-search"></span>搜索
                </button>
            </form>
            <div class="table-responsive">
                <table id="table"></table>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div
        class="modal fade bd-example-modal-lg"
        id="myModal"
        tabindex="-1"
        role="dialog"
        aria-labelledby="myModalLabel"
>
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">新增用户信息</h4>
                <div class="col-md-2 column"></div>
                <div class="col-md-4 column" id="close"></div>
                <button
                        type="button"
                        class="close"
                        data-dismiss="modal"
                        aria-label="Close"
                >
                    <a aria-hidden="true">&times;</a>
                </button>
            </div>
            <div class="modal-body" style="background-color: #f8faf7">
                <!-- 增加修改表单 -->
                <div class="table-responsive">
                    <form>
                        <table class="table table-bordered table-hover" id="tab333">
                            <input type="hidden" name="id"/>
                            <input type="hidden" name="userImg" value="title01.png"/>
                            <tr>
                                <td>用户名：</td>
                                <td>
                                    <label
                                    ><input
                                            name="username"
                                            class="form-control"
                                            placeholder="请输入用户名"
                                    /></label>
                                </td>
                                <td>真实姓名：</td>
                                <td>
                                    <label
                                    ><input
                                            name="nickname"
                                            class="form-control"
                                            placeholder="请输入真实姓名"
                                    /></label>
                                </td>
                            </tr>
                            <tr>
                                <td>邮箱：</td>
                                <td>
                                    <label
                                    ><input
                                            name="userEmail"
                                            class="form-control"
                                            placeholder="请输入邮箱"
                                    /></label>
                                </td>
                                <td>联系电话：</td>
                                <td>
                                    <label
                                    ><input
                                            name="userPhone"
                                            class="form-control"
                                            placeholder="请输入联系电话"
                                    /></label>
                                </td>
                            </tr>
                            <tr>
                                <td>状态：</td>
                                <td>
                                    <div
                                            class="custom-control custom-radio custom-control-inline"
                                    >
                                        <input
                                                type="radio"
                                                id="customRadioInline1"
                                                name="isValid"
                                                value="1"
                                                checked="checked"
                                                class="custom-control-input"
                                        />
                                        <label
                                                class="custom-control-label"
                                                for="customRadioInline1"
                                        >有效</label
                                        >
                                    </div>
                                    <div
                                            class="custom-control custom-radio custom-control-inline"
                                    >
                                        <input
                                                type="radio"
                                                id="customRadioInline2"
                                                name="isValid"
                                                value="0"
                                                class="custom-control-input"
                                        />
                                        <label
                                                class="custom-control-label"
                                                for="customRadioInline2"
                                        >无效</label
                                        >
                                    </div>
                                </td>
                                <td>角色：</td>
                                <td>
                                    <label>
                                        <select
                                                name="roleIds"
                                                multiple
                                                style="min-height: 100px; min-width: 100px"
                                        ></select>
                                    </label>
                                </td>
                            </tr>
                        </table>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    关闭
                </button>
                <button
                        type="button"
                        id="btn111"
                        class="btn btn-primary"
                        onclick="insert_update()"
                >
                    修改
                </button>
            </div>
        </div>
    </div>
</div>
<script>
    $(function () {
        // 初始化表格
        $('#table').bootstrapTable({
            classes: 'table table-bordered table-hover table-striped',
            url: '${ctx}/user/list',
            method: 'GET',
            toolbar: '#toolbar', // 工具按钮容器
            pagination: true,
            pageNumber: 1,
            pageSize: 5,
            paginationLoop: false,
            pageList: [5, 10, 20],
            clickToSelect: true, // 是否启用点击选中行
            showFullscreen: true, // 显示全屏
            undefinedText: '-', // 当字段为 undefined 显示
            sortOrder: "asc", // 排序方式
            showColumns: true, // 是否显示所有的列
            showRefresh: true, // 是否显示刷新按钮
            showToggle: true, // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)
            showExport: true,        // 是否显示导出按钮, 导出功能需要导出插件支持(tableexport.min.js)
            exportDataType: "all", // 导出数据类型, 'basic':当前页, 'all':所有数据, 'selected':选中的数据
            // 响应处理
            responseHandler: function (res) {
                if (res.code !== 200) {
                    notify("mdi mdi-close", res.message, "danger");
                    return [];
                }

                return res.data;
            },
            // 查询参数
            queryParams: function () {
                return $("form:eq(0)").serializeArray();
            },
            columns: [{
                field: 'example',
                checkbox: true
            }, {
                field: 'no',
                align: 'center',
                title: '序号',
                formatter: function (value, row, index) {
                    //返回序号，注意index是从0开始的，所以要加上1
                    return index + 1;
                }
            }, {
                field: 'id',
                title: '编号',
                visible: false
            }, {
                field: 'username',
                align: 'center',
                title: '用户名称'
            }, {
                field: 'nickname',
                align: 'center',
                title: '真实姓名'
            }, {
                field: 'userEmail',
                align: 'center',
                title: '邮箱'
            }, {
                field: 'userPhone',
                align: 'center',
                title: '联系电话'
            }, {
                field: 'isValid',
                align: 'center',
                title: '状态',
                formatter: function (value, row) {     // 格式化
                    if (row.isValid === 1) {
                        return "<span class='badge badge-success'>有效</sapn>";
                    } else if (row.isValid === 0) {
                        return "<span class='badge badge-danger'>无效</span>";
                    } else {
                        return "<span class='badge badge-info'>-</span>";
                    }
                }
            }, {
                field: 'createDate',
                align: 'center',
                title: '创建时间'
            },{
                field: 'operate',
                align: 'center',
                title: '操作',
                formatter: btnGroup,
                events: {
                    'click .edit-btn': function (event, value, row) {
                        if (validAccount(row.id)) {
                            edit(row);
                        }
                    },
                    'click .del-btn': function (event, value, row) {
                        if (validAccount(row.id)) {
                            remove('user', row.id);
                        }
                    },
                    'click .refresh-btn': function (event, value, row) {
                        if (validAccount(row.id)) {
                            resetPwd(row);
                        }
                    }
                }
            }],
            onLoadSuccess: function () {      // 数据加载成功时调用的方法
            },
            onLoadError: function () {        // 数据加载失败时调用的方法
                setTimeout(function () {
                    notify("mdi mdi-close", "数据加载失败!", "danger");
                }, 300);
            },
            onCheck: function () {        // 复选框选中事件
                getSelections();
            }
        });

        // 用户角色
        $.get("${ctx}/role/list", function (res) {
            $(res.data).each(function (i, obj) {
                let $option = $("<option value='" + obj.id + "'>" + obj.roleName + "</option>");
                $("[name='roleIds']").append($option);
            });
        });
    });

    /**
     * 验证用户
     * @param id ID
     * @returns {boolean}
     */
    function validAccount(id) {
        if (id === 1) {
            setTimeout(function () {
                notify("mdi mdi-alert-octagon-outline", "超级管理员不能修改!", "warning");
            }, 300);
            return false;
        }

        if (id === ${sessionScope.session_user.id}) {
            setTimeout(function () {
                notify("mdi mdi-alert-octagon-outline", "暂不支持修改自己!", "warning");
            }, 300);
            return false;
        }

        return true;
    }


    // 操作按钮
    function btnGroup() {
        return '<a href="#" class="btn btn-xs btn-success m-r-5 edit-btn" title="编辑" data-toggle="tooltip"><span class="mdi mdi-pencil"></span>编辑</a>' +
            '<a href="#" class="btn btn-xs btn-danger m-r-5 del-btn confirm" title="删除" data-toggle="tooltip"><span class="mdi mdi-window-close"></span>删除</a>' +
            '<a href="#" class="btn btn-xs btn-primary m-r-5 refresh-btn confirm" title="重置密码" data-toggle="tooltip"><span class="mdi mdi-refresh"></span>重置密码</a>';
    }

    // 操作方法 - 新增
    function toAdd() {
        $("#myModal").modal("show");
        $("#myModalLabel").html("新增用户信息");
        $("form")[1].reset();
        $("#btn111").html("保存");
    }

    // 操作方法 - 重置密码
    function resetPwd(r) {
        $.confirm({
            title: '重置密码(默认密码为: 123456)',
            content: '您确定要重置 ' + r.nickname + ' 的密码吗？',
            type: 'blue',
            icon: 'mdi mdi-refresh',
            typeAnimated: true,
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-blue',
                    action: function () {
                        let loader = $('body').lyearloading({
                            opacity: 0.2,
                            spinnerSize: 'lg',
                            spinnerText: '正在重置密码中...',
                            textColorClass: 'text-info',
                            spinnerColorClass: 'text-info',
                        });
                        setTimeout(function () {
                            $.post("${ctx}/user/reset-password", "uId=" + r.id, function (data) {
                                loader.destroy();
                                if (data.code === 200) {
                                    // 刷新表格
                                    $('#table').bootstrapTable("refresh");
                                    notify("mdi mdi-checkbox-marked-circle-outline", data.message, "success");
                                } else {
                                    notify("mdi mdi-close", data.message, "danger");
                                }
                            });
                        }, 1e3);
                    }
                },
                cancel: {   // 取消按钮
                    text: '取消',
                    action: function () {
                    }
                }
            },
        });
    }

    // 操作方法 - 编辑
    function edit(r) {
        $("#myModal").modal("show");
        $("#myModalLabel").html("修改用户信息");
        $("input[name='id']").val(r.id);
        $("input[name='username']:eq(1)").val(r.username);
        $("input[name='nickname']").val(r.nickname);
        $("input[name='userEmail']").val(r.userEmail);
        $("input[name='userPhone']:eq(1)").val(r.userPhone);
        (r.isValid) ? $("[name='isValid']:first").prop("checked", true) : $("[name='isValid']:last").prop("checked", true);
        $("input[name='userImg']").val(r.userImg);
        $("[name='roleIds']").val(r.roleIds);

        // 将按钮改为修改
        $("#btn111").html("修改");
    }


    // 修改和增加用一个按钮
    function insert_update() {
        let b = false;

        let $username = $("[name='username']:eq(1)");
        let $nickname = $("[name='nickname']");
        let $usersEmail = $("[name='userEmail']");
        let $usersPhone = $("[name='userPhone']:eq(1)");
        let $roleIds = $("[name='roleIds']");
        let emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;

        if ($username.val() === '${sessionScope.session_user.username}') {
            notify("mdi mdi-close", "暂不支持修改自己！", "danger");
        } else if ($username.val() === '') {
            notify("mdi mdi-close", "用户名为必填项！", "danger");
            $username.focus();
        } else if ($nickname.val() === '') {
            notify("mdi mdi-close", "真实姓名为必填项！", "danger");
            $nickname.focus();
        } else if ($usersEmail.val() === '') {
            notify("mdi mdi-close", "邮箱为必填项！", "danger");
            $usersEmail.focus();
        } else if (!emailReg.test($usersEmail.val())) {
            notify("mdi mdi-close", "邮箱格式错误！请输入正确的邮箱...", "danger");
            $usersEmail.focus();
        } else if ($usersPhone.val() === '') {
            notify("mdi mdi-close", "联系电话为必填项！", "danger");
            $usersPhone.focus();
        } else if (!phoneReg.test($usersPhone.val())) {
            notify("mdi mdi-close", "电话号码格式错误！请输入正确的电话号码...", "danger");
            $usersPhone.focus();
        } else if ($roleIds.val() === '') {
            notify("mdi mdi-close", "请选择角色！", "danger");
            $roleIds.focus();
        } else {
            b = true;
        }

        // 根据按钮判断增加还是修改
        let url = ($("#btn111").html() === '保存') ? "${ctx}/user/save" : "${ctx}/user/update";

        if (b) {
            // 得到表单的值
            let obj = $("form:eq(1)").serializeArray();
            saveOrUpdate(url, obj)
        }
    }


    // 操作方法 - 批量删除
    function batchDel() {
        if (getSelections().includes(1)) {
            setTimeout(function () {
                notify("mdi mdi-close", "管理员账户不能删除~", "danger");
            }, 1e2);
        } else if (getSelections().includes(${sessionScope.session_user.id})) {
            setTimeout(function () {
                notify("mdi mdi-close", "不可以删除自己哦~", "danger");
            }, 1e2);
        } else {
            batchDelete("user")
        }
    }
</script>
</body>
</html>
